package cn.kgc.mushroomdatabaseprovider.service.serviceimpl;

import cn.kgc.mushroomcommon.pojo.User;
import cn.kgc.mushroomcommon.pojo.UserExample;
import cn.kgc.mushroomcommon.util.CrowdUtils;
import cn.kgc.mushroomdatabaseprovider.mapper.UserMapper;
import cn.kgc.mushroomdatabaseprovider.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Override
    public User getUserByAccount(String account) {
        UserExample example = new UserExample();
        example.createCriteria().andAccountEqualTo(account);
        List<User> userList = userMapper.selectByExample(example);
        if(CrowdUtils.collectionEffectiveCheck(userList)) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public User getUserByPhone(String phone) {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(phone);
        List<User> userList = userMapper.selectByExample(example);
        if(CrowdUtils.collectionEffectiveCheck(userList)) {
            return userList.get(0);
        }
        return null;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public int saveUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public Integer getAccountCount(String account) {
        UserExample example = new UserExample();
        example.createCriteria().andAccountEqualTo(account);
        return userMapper.countByExample(example);
    }

    @Override
    public Integer getPhoneCount(String phone) {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(phone);
        return userMapper.countByExample(example);
    }
}
